import React, { useImperativeHandle, useState, useEffect } from 'react';
import { connect } from 'dva';
import { Form, Input, Select, DatePicker } from 'antd';
import TitleLine from 'components/common/titleLine';
import UploadPic from 'components/common/uploadPic';
import UploadPicIE from 'components/common/uploadPicIE';
import moment from 'moment';
import locale from 'antd/es/date-picker/locale/zh_CN';
import 'moment/locale/zh-cn';
import './index.styl';
import { fitterInput } from 'utils/filters'
import { IsIE_nine } from 'utils/format'

const { Option } = Select;
const { TextArea } = Input;
const { MonthPicker } = DatePicker;

function BasicInfo({ dictionaryList: { dicList, groupList }, cRef, dispatch, actionType, id, deviceLedger: { notNo, detail }, form }) {
  const [deviceImage, setImgSrc] = useState('');
  const [deviceNo, setDeviceNo] = useState('');
  const { getFieldDecorator, resetFields, validateFields, getFieldsValue, setFieldsValue } = form;
  const [imageList, setImageList] = useState('')

  useEffect(() => {
    if (id) {
      setFieldsValue({
        deviceName: detail && detail.deviceName,
        deviceNo: detail && detail.deviceNo,
        deviceLevel: detail && detail.deviceLevel,
        deviceType: detail && detail.deviceType,
        groupId: detail && detail.groupId,
        chargePerson: detail && detail.chargePerson,
        productTime: detail && detail.productTime && moment(detail.productTime, 'YYYY-MM'),
        useTime: detail && detail.useTime && moment(detail.useTime, 'YYYY-MM'),
        price: detail && detail.price,
        supplier: detail && detail.supplier,
        factoryNo: detail && detail.factoryNo,
        ratePower: detail && detail.ratePower,
        weight: detail && detail.weight,
        length: detail && detail.length,
        width: detail && detail.width,
        height: detail && detail.height,
        address: detail && detail.address,
        remark: detail && detail.remark,
      });
      setImageList(detail.deviceImage)
    }
  }, [setFieldsValue, detail, id]);
  useEffect(() => {
    dispatch({
      type: 'dictionaryList/getGroupList',
    });
    // 获取字典
    dispatch({
      type: 'dictionaryList/getList',
    });
  }, [dispatch])
  useImperativeHandle(cRef, () => ({
    values: getFieldsValue(),
    deviceImage,
    validateFields,
    resetFields,
  }));

  function checkDeviceNo(v) {
    if (v !== '') {
      if (actionType === 'edit' && detail.deviceNo === v) {
        // 更改编号重复状态
        dispatch({
          type: 'deviceLedger/changeNoCheck',
        });
        return
      }
      dispatch({
        type: 'deviceLedger/deviceNoCheck',
        payload: { num: v },
      });
    } else {
      dispatch({
        type: 'deviceLedger/changeNoCheck',
      })
    }
  }

  // 生产日期
  const [startTime, setStartTime] = useState()
  // 投产日期
  const [endTime, setEndTime] = useState()

  // // 生产日期
  // const selectStartTime = (time, str) => {
  //   setStartTime(time)
  // }

  // // 投产日期
  // const selectEndTime = (time, str) => {
  //   setEndTime(time)
  // }


  // 设备描述字数统计
  const [len, setRemarkValue] = useState(0)
  const remarkValue = (e) => {
    const len = e.target.value.replace(/\s/g,"").trim().length
    if (len <= 200) {
      setRemarkValue(len)
    } else {
      setRemarkValue(200)
    }
  }

  // 设置生产不能选择的时间
  const disabledDate = date => {
    return date && date > moment().endOf('day');
  }

  return (
    <div className="BasicInfo">
      <TitleLine title={'设备台账基本信息'} />
      <Form name="nest-messages" className="self-form">
        <div className="flex">
          <Form.Item label="设备名称" colon={false}>
            {getFieldDecorator('deviceName', {
              rules: [
                { required: true, message: '请输入设备名称' },
                { max: 20, message: '最多可输入20字' },
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(<Input className="self-input" placeholder="请输入设备名称" maxLength={20} />)}
          </Form.Item>
          <Form.Item label="设备编号" colon={false}>
            {getFieldDecorator('deviceNo', {
              rules: [
                { required: true, message: '请输入设备编号' },
                { max: 20, message: '最多可输入20字' },
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(
              <Input
                className="self-input"
                placeholder="请输入"
                maxLength={20}
                onChange={v => {
                  checkDeviceNo(v.target.value);
                  setDeviceNo(v.target.value);
                }}
              />,
            )}
            {!notNo && deviceNo ? <div className="tipNo">设备编号重复</div> : null}
          </Form.Item>
          <Form.Item label="设备级别" colon={false}>
            {getFieldDecorator('deviceLevel', {
              rules: [{ required: true, message: '请选择设备级别' }],
              validateTrigger: ['onBlur', 'onChange']
            })(
              <Select placeholder="请选择" className="self-select" getPopupContainer={triggerNode => triggerNode.parentNode}>
                {dicList.deviceLevelList &&
                  dicList.deviceLevelList.map(item => {
                    return (
                      <Option value={item.code} key={item.code}>
                        {item.desc}
                      </Option>
                    );
                  })}
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="设备类型" colon={false}>
            {getFieldDecorator('deviceType', {
              rules: [{ required: true, message: '请选择设备类型' }],
              validateTrigger: ['onBlur', 'onChange']
            })(
              <Select className="self-select" placeholder="请选择" disabled={actionType === 'edit' ? true : false} getPopupContainer={triggerNode => triggerNode.parentNode}>
                {dicList.deviceTypeList &&
                  dicList.deviceTypeList.map(item => {
                    return (
                      <Option value={item.id} key={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="使用部门" colon={false}>
            {getFieldDecorator('groupId', {
              rules: [{ required: true, message: '请选择使用部门' }],
              validateTrigger: ['onBlur', 'onChange']
            })(
              <Select
                placeholder="请选择"
                className="self-select"
                getPopupContainer={triggerNode => triggerNode.parentNode}
              >
                {groupList.length &&
                  groupList.map(item => {
                    return (
                      <Option value={item.id} key={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
              </Select>,
            )}
          </Form.Item>
        </div>
        <div className="flex">
          <Form.Item label="责任人" colon={false}>
            {getFieldDecorator('chargePerson', {
              rules: [
                { required: true, message: '请输入责任人' },
                { max: 5, message: '最多可输入5字' },
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(<Input className="self-input" placeholder="请输入" maxLength={5} />)}
          </Form.Item>
          <Form.Item label="生产日期" colon={false}>
            {getFieldDecorator('productTime', {
              rules: [
                { required: true, message: '请选择生产日期' },
                {
                  validator: (rule, value, callback) => {
                    if (value && endTime) {
                      if (moment(value._d).format('YYYY-MM') > moment(endTime._d).format('YYYY-MM')) {
                        callback('不能晚于投产日期')
                      }
                    }
                    callback()
                  }
                }
              ],
            })(
              <DatePicker.MonthPicker
                className="self-date"
                showToday={false}
                format={'YYYY-MM'}
                onChange={(t, s) => setStartTime(t)}
                placeholder="请选择日期"
                disabledDate={disabledDate}
                picker="month"
                onBlur={() => validateFields(['productTime'])}
                locale={locale}
                allowClear={false}
              />,
            )}
          </Form.Item>
          <Form.Item label="投产日期" colon={false}>
            {getFieldDecorator('useTime', {
              rules: [
                { required: true, message: '请选择投产日期' },
                {
                  validator: (rule, value, callback) => {
                    if (value && startTime) {
                      if (moment(value._d).format('YYYY-MM') < moment(startTime._d).format('YYYY-MM')) {
                        callback('不能早于生产日期')
                      }
                    }
                    callback()
                  }
                }
              ],
            })(
              <MonthPicker
                allowClear={false}
                className="self-date"
                showToday={false}
                format={'YYYY-MM'}
                onChange={(t, s) => setEndTime(t)}
                disabledDate={disabledDate}
                placeholder="请选择日期"
                onBlur={() => validateFields(['useTime'])}
                locale={locale}
              />,
            )}
          </Form.Item>
          <Form.Item label="设备金额" className="devicePrice" colon={false}>
            {getFieldDecorator('price', {
              rules: [
                { required: true, message: '请输入正确的设备金额' },
                { max: 10, message: '最多可输入10字' },
                { pattern: /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/, message: '请输入数字，最多两位小数' },
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(
              <Input
                className="self-input"
                placeholder="请输入"
                suffix="万"
                maxLength={10}
              />,
            )}
          </Form.Item>
          <Form.Item label="供应商" colon={false}>
            {getFieldDecorator('supplier', {
              rules: [
                { required: false },
                { max: 20, message: '最多可输入20字' },
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(<Input className="self-input" placeholder="请输入" maxLength={20} />)}
          </Form.Item>
        </div>

        <div className="flex">
          <Form.Item label="出厂编号" colon={false}>
            {getFieldDecorator('factoryNo', {
              rules: [
                { required: false },
                { max: 20, message: '最多可输入20字' },
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(<Input className="self-input" placeholder="请输入" maxLength={20} />)}
          </Form.Item>
          <Form.Item label="额定功率" colon={false}>
            {getFieldDecorator('ratePower', {
              rules: [
                { required: false },
                { max: 10, message: '最多可输入10字' },
                { pattern: /^\d*(?:\.\d{1,2})?$/, message: '请输入数字，最多两位小数' }
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(
              <Input
                className="self-input"
                placeholder="请输入"
                suffix="KW"
                maxLength={10}
              />,
            )}
          </Form.Item>
          <Form.Item label="重量" colon={false}>
            {getFieldDecorator('weight', {
              rules: [
                { required: false },
                { max: 10, message: '最多可输入10字' },
                { pattern: /^\d*(?:\.\d{1,2})?$/, message: '请输入数字，最多两位小数' }
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(
              <Input
                className="self-input"
                placeholder="请输入"
                suffix="吨"
                maxLength={10}
              />,
            )}
          </Form.Item>
          <Form.Item label="长" className="area" colon={false}>
            {getFieldDecorator('length', {
              rules: [
                { required: false },
                { max: 10, message: '最多可输入10字' },
                { pattern: /^\d+(?:\.\d{1,2})?$/, message: '请输入数字，最多两位小数' }
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(
              <Input
                className="self-input"
                placeholder="请输入"
                suffix="米"
                maxLength={10}
              />,
            )}
          </Form.Item>
          <Form.Item label="宽" className="area" colon={false}>
            {getFieldDecorator('width', {
              rules: [
                { required: false },
                { max: 10, message: '最多可输入10字' },
                { pattern: /^\d*(?:\.\d{1,2})?$/, message: '请输入数字，最多两位小数' }
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(
              <Input
                className="self-input"
                placeholder="请输入"
                suffix="米"
                maxLength={10}
              />,
            )}
          </Form.Item>
          <Form.Item label="高" className="area" colon={false}>
            {getFieldDecorator('height', {
              rules: [
                { required: false },
                { max: 10, message: '最多可输入10字' },
                { pattern: /^\d*(?:\.\d{1,2})?$/, message: '请输入数字，最多两位小数' }
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(
              <Input
                className="self-input"
                placeholder="请输入"
                suffix="米"
                maxLength={10}
              />,
            )}
          </Form.Item>
        </div>
        <div className="flex address">
          <Form.Item label="设备地址" colon={false}>
            {getFieldDecorator('address', {
              rules: [
                { required: false },
                { max: 50, message: '最多可输入50字' },
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(<Input className="self-input" placeholder="请输入" maxLength={50} />)}
          </Form.Item>
        </div>
        <div className="flex address deviceDescri">
          <Form.Item label="设备描述" colon={false}>
            {getFieldDecorator('remark', {
              rules: [
                { required: false },
                { max: 200, message: '最多可输入200字' },
                // { pattern: /^[^\s]*$/,message: '禁止输入空格'}
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput,''),
              validateTrigger: ['onBlur', 'onChange']
            })(<TextArea cols={6} placeholder="请输入" maxLength={200} onChange={remarkValue}  />)}
            <div style={{ position: 'absolute', right: '0' }}>{len}/200</div>
          </Form.Item>
        </div>
      </Form>
      <div className="flex picWrapper">
        <div className="deviceTitle">设备主图</div>
        {
          IsIE_nine() === 9 ? (<UploadPicIE index={1} getImgSrc={v => { setImgSrc(v) }} editImg={imageList} />) : (
            <UploadPic getImgSrc={v => { setImgSrc(v) }} editImg={imageList} />
          )
        }
      </div>
    </div>
  );
}

export default connect(({ deviceLedger, dictionaryList }) => ({
  deviceLedger,
  dictionaryList
}))(Form.create()(BasicInfo));
